import pickle
import gradio as gr
import numpy as np
from PIL import Image

with open('best_knn_model.pkl', 'rb') as f:
    model = pickle.load(f)
def predict_digit(image):
    try:
        img = Image.fromarray(image).convert('L')
        img = img.resize((8, 8))
        img_array = np.array(img)
        img_array = 16 - (img_array / 16).astype(int)
        img_flat = img_array.flatten().reshape(1, -1)
        
        prediction = model.predict(img_flat)[0]
        return f"shibie jieguo: {prediction}"
    except Exception as e:
        return f"cuowu: {str(e)}"
demo = gr.Interface(
    predict_digit,
    gr.Image(shape=(28, 28), image_mode="L", source="canvas"),
    "text",
    title="shouxie shuzi shibieqi",
    description="hua yige shuzi (0-9), dianji tijiao shibie"
)

demo.launch()

